package TreeSeries;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class LevelOrderBottomSolution_107 {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();

        List<List<Integer>> result = new ArrayList<>();
        if (root == null) return result;
        queue.offer(root);

        while (!queue.isEmpty()) {
            List<Integer> res = new ArrayList<>();
            int queueSize = queue.size();
            for (int i = 0; i < queueSize; i++) {
                TreeNode node = queue.poll();
                res.add(node.val);
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
            result.add(res);
        }
        List<List<Integer>> result_reverse = new ArrayList<>();
        for (int i = result.size() - 1; i >= 0; i--) {
            result_reverse.add(result.get(i));
        }
        return result_reverse;
    }


}
